package com.lqian.simplestructure.linearlist;


/**
 * 二分法查找(要求数列有序)
 */
public class BinarySearch {
    public static void main(String[] args) {
        //目标数组
        int[] arr = new int[]{1,2,3,4,5,6,7,8,9};
        //目标元素
        int target = 3;
        int begin = 0;
        int end = arr.length-1;
        int mid = (begin + end) / 2;
        //目标索引下标
        int index = -1;
        while(true){
            if (arr[mid] == target){
                index = mid;
                break;
            }else{
                if (arr[mid]>target){
                        end = mid - 1;
                }else {
                    begin = mid + 1;
                }
                //重新取出中间位置
                mid = (begin + end)/2;
            }
        }

        System.out.println("index:"+index);
    }

}
